from flask import Flask, request, jsonify, send_from_directory
import numpy as np
from datetime import datetime
import pytz
from rabbitmq_utils import init_rabbitmq
from rabbitmq_utils import send_to_multitask_rabbitmq
from threading import Thread
import time
import traceback
from flask_socketio import SocketIO, emit
from dummy_data import dummy_data
from rabbitmq_consumers import rabbitmq_consumer, rabbitmq_multitask_consumer
from log_utils import log_request

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")

# 获取北京时间
def get_beijing_time():
    tz = pytz.timezone('Asia/Shanghai')
    return datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')

@app.route('/submit', methods=['POST'])
def submit():
    try:
        data = request.get_json(force=True)
        np_array = np.array(data)
        message = {
            'time': get_beijing_time(),
            'type': 'demo',
            'data': data
        }
        from rabbitmq_utils import send_to_rabbitmq
        send_to_rabbitmq(message)
        return jsonify({'code': 200})
    except Exception as e:
        print(f"[ERROR] {str(e)}")
        return jsonify({'code': 500, 'message': str(e)}), 500

@app.route('/submit_multitask', methods=['POST'])
def submit_multitask():
    try:
        
        # 尝试不同的文件接收方式
        binary_file = None
        
        # 方法1：检查是否有文件上传
        if 'file' in request.files:
            file = request.files['file']
            if file:
                binary_file = file.read()
                print(f"[DEBUG] 通过 request.files 获取文件，大小: {len(binary_file)}")
        
        # # 方法2：使用 request.data
        # if not binary_file:
        #     binary_file = request.data
        #     print(f"[DEBUG] 通过 request.data 获取数据，大小: {len(binary_file) if binary_file else 0}")
        
        if not binary_file:
            return jsonify({'code': 400, 'message': '没有接收到文件数据'}), 400
        
        # 将文件保存为临时文件
        import tempfile
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_file.write(binary_file)
            temp_file_path = temp_file.name
            print(f"[DEBUG] 临时文件保存到: {temp_file_path}")
            print(f"[DEBUG] 临时文件大小: {len(binary_file)} 字节")
            
            # 验证文件是否写入成功
            import os
            if os.path.exists(temp_file_path):
                file_size = os.path.getsize(temp_file_path)
                print(f"[DEBUG] 文件实际大小: {file_size} 字节")
            
            data = dummy_data(temp_file_path)
        
        message = {
            'time': get_beijing_time(),
            'type': 'multitask',
            'data': data
        }
        from rabbitmq_utils import send_to_multitask_rabbitmq
        send_to_multitask_rabbitmq(message)

        # 将处理后的数据返回给客户端
        return jsonify(data)
    except Exception as e:
        print(f"[ERROR] {str(e)}")
        return jsonify({'code': 500, 'message': str(e)}), 500        

@app.route('/submit_json', methods=['POST'])
def submit_json():
    try:
        if request.headers.get('request-id'):
            request_id:str = request.headers.get('request-id')
        else:
            request_id:str = None
        if request.headers.get('request-time'):
            request_time:int = int(request.headers.get('request-time'))
        else:
            request_time:int = -1
        accept_time:int = int(time.time() * 1000)
        data = request.get_json(force=True)
        request_body:str = request.data
        message = data
        message['time'] = get_beijing_time()
        
        send_to_multitask_rabbitmq(message)
        finished_time:int = int(time.time() * 1000)
        
        log_request(request_id=request_id, request_type="submit_json", request_time=request_time, 
            accept_time=accept_time, finished_time=finished_time, request_body=request_body)
        return jsonify({'code': 200})
    except Exception as e:
        traceback.print_exc()
        print(f"[ERROR] {str(e)}")
        return jsonify({'code': 500, 'message': str(e)}), 500

@app.route('/')
def index():
    return send_from_directory('static', 'index.html')

@app.route('/dashboard_data')
def dashboard_data():
    return jsonify(dummy_data())

@app.route('/<path:path>')
def static_proxy(path):
    return send_from_directory('static', path)

# WebSocket 入口
@socketio.on('connect', namespace='/ws')
def ws_connect():
    print('WebSocket client connected')

@socketio.on('disconnect', namespace='/ws')
def ws_disconnect():
    print('WebSocket client disconnected')

# WebSocket 入口
@socketio.on('connect', namespace='/multitask')
def multitask_connect():
    print('WebSocket multitask client connected')

@socketio.on('disconnect', namespace='/multitask')
def multitask_disconnect():
    print('WebSocket multitask client disconnected')



if __name__ == '__main__':
    init_rabbitmq()
    # 启动RabbitMQ消费线程
    consumer_thread = Thread(target=rabbitmq_consumer, args=(socketio,), daemon=True)
    consumer_thread.start()

    multitask_consumer_thread = Thread(target=rabbitmq_multitask_consumer, args=(socketio,), daemon=True)
    multitask_consumer_thread.start()

    socketio.run(app, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=True) 
